package com.wgke.bluetooth.ui;

import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.content.Intent;
import android.net.Uri;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;

import androidx.appcompat.widget.PopupMenu;

import com.wgke.bluetooth.R;
import com.wgke.bluetooth.db.CmdEntity;
import com.wgke.bluetooth.tools.BtMsg;
import com.wgke.bluetooth.utils.Async;
import com.wgke.bluetooth.utils.FileUtil;
import com.wgke.bluetooth.utils.ToastUtil;
import com.wgke.bluetooth.vm.SettingsVM;

public class SettingActivity extends BaseListActivity<SettingsVM> {
    View settingsPopup;


    @Override
    public int layoutId() {
        return R.layout.activity_settings;
    }

    @Override
    public int itemId() {
        return R.layout.item_cmd;
    }

    @Override
    public void finish() {
        if (settingsPopup != null && settingsPopup.getVisibility() == View.VISIBLE) {
            settingsPopup.setVisibility(View.GONE);
            return;
        }
        super.finish();
    }

    @Override
    protected void initStateBar() {
        super.initStateBar();
        initToolbar("蓝牙指令管理");
    }

    @Override
    public void initOtherView() {
        findViewById(R.id.ivMore).setOnClickListener(v -> {
            showPopupMenu(v);
        });
        vm.list.observe(this, list -> {
            if (list.isEmpty()) {
                setEmptyAdapter("点击右下角添加命令", R.drawable.baseline_add_24);
            } else {
                setAdapter(list, (h, c) -> {
                    h.setText(R.id.cmdName, c.name);
                    h.setText(R.id.cmdContent, c.cmd);
                    h.getView(R.id.cmdSettings).setOnClickListener(v -> {
                        showCmdInfo(c);
                    });
                    h.getView(R.id.cmdDel).setOnClickListener(v -> {
                        delItem(c, h.getAdapterPosition());
                    });
                });
            }
        });
        findViewById(R.id.fab).setOnClickListener(v -> showCmdInfo(null));

        settingsPopup = findViewById(R.id.settingsPopup);
        vm.loadCmdList();
    }

    public void showCmdInfo(CmdEntity cmdEntity) {
        settingsPopup.setVisibility(View.VISIBLE);
        Button btnSave = findViewById(R.id.btnSave);
        Button btnCancel = findViewById(R.id.btnCancel);
        EditText inputCmdContent = findViewById(R.id.inputCmdContent);
        EditText inputCmdName = findViewById(R.id.inputCmdName);
        if (cmdEntity != null) {
            inputCmdContent.setText(cmdEntity.cmd);
            inputCmdName.setText(cmdEntity.name);
        }
        btnCancel.setOnClickListener(v -> {
            hideKeyboard();
            settingsPopup.setVisibility(View.GONE);
        });
        btnSave.setOnClickListener(v -> {
            saveCmdInfo(inputCmdName.getText().toString(), inputCmdContent.getText().toString(), cmdEntity);
        });
    }

    public void saveCmdInfo(String name, String cmd, CmdEntity cmdEntity) {
        if (TextUtils.isEmpty(name.trim()) || TextUtils.isEmpty(cmd)) {
            ToastUtil.showMsg("请输入有效内容");
            return;
        }
        byte[] bytes = BtMsg.hexStringToByteArray(cmd);
        if (bytes == null) {
            ToastUtil.showMsg("请输入指令不合法");
            return;
        }
        StringBuilder hexString1 = new StringBuilder();
        for (byte b : bytes) {
            hexString1.append(String.format("%02X ", b));
        }
        CmdEntity bean = cmdEntity == null ? new CmdEntity() : cmdEntity;
        bean.name = name;
        bean.cmd = hexString1.toString();
        Runnable runnable = () -> runOnUiThread(() -> {
            ToastUtil.showMsg("操作成功！");
            hideKeyboard();
            settingsPopup.setVisibility(View.GONE);
            vm.loadCmdList();
        });
        if (cmdEntity == null) {
            bean.describe = "";
            bean.time = System.currentTimeMillis();
            Async.getInstance().awaitInsert(bean, runnable);
        } else {
            Async.getInstance().awaitUpdate(bean, runnable);
        }
    }


    @Override
    public void onRefresh() {
        postDelayed(1000, this::finishRefresh);
        vm.loadCmdList();
    }

    @Override
    public void emptyAgain() {
        startRefresh();
        onRefresh();
    }

    public void delItem(CmdEntity bean, int index) {
        new AlertDialog.Builder(this).setTitle("提示").setMessage("确定要删除 " + bean.name + " 吗？").setPositiveButton("删除", (dialog, which) -> {
                    Async.getInstance().await(() -> {
                        Async.getInstance().getDao().delete(bean);
                    });
                    remove(index);
                }).setNeutralButton("取消", (dialog, which) -> {
                    dialog.dismiss();
                }).setCancelable(false) // 是否允许点击外部取消
                .show();
    }

    @Override
    public boolean isUseEventBus() {
        return false;
    }

    public void importDefaultData() {
        vm.createCmd();
    }

    public void clearData() {
        Async.getInstance().await(() -> {
            Async.getInstance().getDao().deleteAll();
            vm.loadCmdList();
        });
    }

    @SuppressLint("NonConstantResourceId")
    private void showPopupMenu(View view) {
        PopupMenu popup = new PopupMenu(this, view);
        popup.getMenuInflater().inflate(R.menu.toolbar_menu, popup.getMenu());
        int resId1 = R.id.action_import_default;
        int resId2 = R.id.action_clear;
        popup.setOnMenuItemClickListener(item -> {
            if (resId1 == item.getItemId()) {
                importDefaultData();
                return true;
            } else if (resId2 == item.getItemId()) {
                clearData();
                return true;
            } else if (R.id.action_import_sd == item.getItemId()) {
                openJsonFilePicker();
                return true;
            }
            return false;
        });
        popup.show();
    }

    private static final int REQUEST_CODE_OPEN_JSON = 1001;

    // 启动文件选择器
    public void openJsonFilePicker() {
        Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT);
        intent.addCategory(Intent.CATEGORY_OPENABLE);
        intent.setType("application/json"); // 限制只选择 .json 文件
        startActivityForResult(intent, REQUEST_CODE_OPEN_JSON);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_CODE_OPEN_JSON && resultCode == RESULT_OK) {
            if (data != null) {
                Uri uri = data.getData();
                Async.getInstance().await(() -> {
                    boolean r = vm.saveJsonToDb(FileUtil.readJsonFile(uri, SettingActivity.this));
                    if (!r) {
                        runOnUiThread(() -> ToastUtil.showLongMsg("读取失败"));
                    }
                });
                // 读取选中的 .json 文件
            }
        }
    }

}
